package com.clp.inflxudb.core.domain;

import lombok.Getter;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

class SimpleDateUtil {
    /**
     * 定义日期格式
     */
    public enum Format {
        yyyyMMdd_HHmmss_SSS("yyyy-MM-dd HH:mm:ss.SSS");

        @Getter
        private String valStr;

        Format(String valStr) {
            this.valStr = valStr;
        }
    }

    private static final SimpleDateFormat REALTIME_DATE_FORMAT = new SimpleDateFormat(Format.yyyyMMdd_HHmmss_SSS.valStr);

    private static Date stringToDate(String str, boolean zero) {
        synchronized (REALTIME_DATE_FORMAT) {
            try {
                return REALTIME_DATE_FORMAT.parse(str);
            } catch (Exception e) {
                return zero ? new Date(0) : new Date();
            }
        }
    }

    /**
     * 时间格式转换
     *
     * @param str 时间字符串
     * @return date对象
     */
    public static Date stringToDateDefaultZero(String str) {
        return stringToDate(str, true);
    }

    public static Date stringToDateDefaultNow(String str) {
        return stringToDate(str, false);
    }

    public static String dateToString(Date timestamp) {
        synchronized (REALTIME_DATE_FORMAT) {
            return REALTIME_DATE_FORMAT.format(timestamp);
        }
    }

    public static Instant stringToInstant(String str) {
        if (str == null) {
            return null;
        }
        return Instant.parse(str);
    }

    /**
     * 获取时间
     * @return
     */
    public static Instant getNowInstant() {
        return  Instant.now();
    }

    public static Date getNowDate() {
        return new Date();
    }

    public static Date getZeroDate() {
        return new Date(0);
    }

    public static Instant dateToInstant(Date date) {
        if (date == null) {
            return getNowInstant();
        }
        return date.toInstant();
    }

    public static Date instantToDate(Instant instant) {
        return Date.from(instant);
    }
}
